package com.hangzhou.welbeing.welbeinginstrument.fragement;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hangzhou.welbeing.welbeinginstrument.R;
import com.hangzhou.welbeing.welbeinginstrument.activity.SimilarProfilePageFocusedActivity;
import com.hangzhou.welbeing.welbeinginstrument.activity.TrueCircleActivity;
import com.hangzhou.welbeing.welbeinginstrument.adapter.MoreCircleAdapter;
import com.hangzhou.welbeing.welbeinginstrument.adapter.MyCircleAdapter;
import com.hangzhou.welbeing.welbeinginstrument.base.MyApplication;
import com.hangzhou.welbeing.welbeinginstrument.bean.AddCircleBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.PayAttentionCirclePostDateBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.PayAttentionToDateBean;
import com.hangzhou.welbeing.welbeinginstrument.config.RBConstants;
import com.hangzhou.welbeing.welbeinginstrument.inteface.OnRecyclerViewItemClickListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 时间 2017 年 08 月 24.
 * 作者 Administrator  刘传华
 * 公司 杭州惟君医疗科技有限公司
 * 包名 com.hangzhou.welbeing.pregnant.welbeing_pregnant.fragement
 * 工程名 welbeing_pregnant
 *
 * @desc 关注  Fragment
 */
public class PayAttentionToFragment extends Fragment  {


    private static final String TAG = "PayAttentionToFragment";
    @Bind(R.id.fragment_pay_attention_to_RecyclerView_01)
    RecyclerView fragmentPayAttentionToRecyclerView01;
    @Bind(R.id.fragment_pay_attention_to_RecyclerView_02)
    RecyclerView fragmentPayAttentionToRecyclerView02;
    private MyCircleAdapter myCircleAdapter;
   // private List<PayAttentionToDateBean.DataBean> mlist;
    private MoreCircleAdapter moreCircleAdapter;
    private List<PayAttentionCirclePostDateBean.DataBean> mdate;

    private Context  mceontn = MyApplication.getMcontext();
    private int lastVisibleItem;
    private int p1 = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(container.getContext(), R.layout.fragment_pay_attention_to, null);
        ButterKnife.bind(this, view);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        fragmentPayAttentionToRecyclerView01.setLayoutManager(layoutManager);



        LinearLayoutManager layoutManager_01 = new LinearLayoutManager(getContext());
        layoutManager_01.setOrientation(LinearLayoutManager.VERTICAL);
        fragmentPayAttentionToRecyclerView02.setLayoutManager(layoutManager_01);
        moreCircleAdapter = new MoreCircleAdapter(mceontn);
        fragmentPayAttentionToRecyclerView02.setAdapter(moreCircleAdapter);
        moreCircleAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view) {
                int position = fragmentPayAttentionToRecyclerView02.getChildAdapterPosition(view);
                Intent intent = new Intent(getContext(), SimilarProfilePageFocusedActivity.class);
                intent.putExtra("po_id",mdate.get(position).po_id);
                intent.putExtra("po_url",mdate.get(position).po_url);
                intent.putExtra("po_name",mdate.get(position).po_name);
                intent.putExtra("content",mdate.get(position).content);
                intent.putExtra("cus_logo",mdate.get(position).cus_logo);
                intent.putExtra("addtime",mdate.get(position).addtime);
                intent.putExtra("cus_name",mdate.get(position).cus_name);
                intent.putExtra("state",mdate.get(position).state+"");
                intent.putExtra("count",mdate.get(position).count+"");
                intent.putExtra("cus_id",mdate.get(position).cus_id+"");
                intent.putExtra("col",mdate.get(position).col+"");
                intent.putExtra("lCount",mdate.get(position).lCount+"");
                intent.putExtra("lstate",mdate.get(position).lstate+"");
                intent.putExtra("hits_like",mdate.get(position).hits_like+"");
                startActivity(intent);
            }

            @Override
            public void onItemFirstButtonClick(View v, int position) {

            }
        });
        fragmentPayAttentionToRecyclerView02.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                //判断RecyclerView的状态 是空闲时，同时，是最后一个可见的ITEM时才加载
                if(newState==RecyclerView.SCROLL_STATE_IDLE&&lastVisibleItem+1==moreCircleAdapter.getItemCount()){
                    moreCircleAdapter.changeMoreStatus(moreCircleAdapter.OPPEN_MORE);
                    //设置正在加载更多
                    moreCircleAdapter.changeMoreStatus(moreCircleAdapter.LOADING_MORE);
                    MyApplication.getmHandler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            p1++;
                            loadPayAttentionCirclePostDate(p1);
                        }
                    },2000);
                    moreCircleAdapter.changeMoreStatus(moreCircleAdapter.PULLUP_LOAD_MORE);
                }

            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //最后一个可见的ITEM
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });


        loadPayAttentionToDate();
        loadPayAttentionCirclePostDate(p1);
        return view;
    }
    /**
     * @desc 关注人发的帖子列表
     * */
    private void loadPayAttentionCirclePostDate(int p) {
        SharedPreferences sp = mceontn.getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.PAY_ATTENTION_CIRCLE_POST)
                .addParams("cus_id", user_id)
                .addParams("p",p+"")
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String praiseParseNetworkResponse =  response.body().string();
                        Gson gson = new Gson();
                      //  Log.e(TAG,"praiseParseNetworkResponse============>"+praiseParseNetworkResponse);
                        final PayAttentionCirclePostDateBean payAttentionCirclePostDateBean =    gson.fromJson(praiseParseNetworkResponse,PayAttentionCirclePostDateBean.class);
                        if(payAttentionCirclePostDateBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    mdate = payAttentionCirclePostDateBean.data;
                                    if(mdate != null){
                                        moreCircleAdapter.addItem(mdate);
                                        moreCircleAdapter.notifyDataSetChanged();
                                        //设置回到上拉加载更多
                                        moreCircleAdapter.changeMoreStatus(moreCircleAdapter.NO_LOAD_MORE);
                                    }

                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),payAttentionCirclePostDateBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }
    /**
     * @desc 加载我的圈子
     * */
    private void loadPayAttentionToDate() {
        SharedPreferences sp = mceontn.getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.MY_CIRCLE)
                .addParams("cus_id",user_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String praiseParseNetworkResponse =  response.body().string();
                        Gson gson = new Gson();
                        Log.e(TAG,"praiseParseNetworkResponse============>"+praiseParseNetworkResponse);
                        final PayAttentionToDateBean payAttentionToDateBean =  gson.fromJson(praiseParseNetworkResponse,PayAttentionToDateBean.class);
                        if(payAttentionToDateBean.errorCode == 200 ){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                  final  List<PayAttentionToDateBean.DataBean>  mlist = payAttentionToDateBean.data;
                                    if(mlist!= null){
                                        myCircleAdapter = new MyCircleAdapter(mceontn,mlist);
                                        fragmentPayAttentionToRecyclerView01.setAdapter(myCircleAdapter);
                                        myCircleAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
                                            @Override
                                            public void onItemClick(View view) {
                                                int position = fragmentPayAttentionToRecyclerView01.getChildAdapterPosition(view);
                                                Intent intent = new Intent(getContext(),TrueCircleActivity.class);
                                                intent.putExtra("circle_id",mlist.get(position).id);
                                                intent.putExtra("circle_num",mlist.get(position).num);
                                                intent.putExtra("circle_name",mlist.get(position).cat_name);
                                                intent.putExtra("circle_state",mlist.get(position).state+"");
                                                intent.putExtra("circle_url",mlist.get(position).url);
                                                startActivity(intent);

                                                SharedPreferences sp =mceontn.getSharedPreferences("second_app_internal_data", 0);
                                                SharedPreferences.Editor edit = sp.edit();
                                                edit.putString("circle_id",mlist.get(position).id);
                                                edit.commit();
                                            }

                                            @Override
                                            public void onItemFirstButtonClick(View v, int position) {
                                                String id =   mlist.get(position).id;
                                                cancel(id);
                                            }
                                        });
                                    }
                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),payAttentionToDateBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }
    /**
     * @desc 取消关注
     * */
    private void cancel(String id) {
        SharedPreferences sp = MyApplication.getMcontext().getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.CANCEL_JOIN)
                .addParams("cat_id",id)
                .addParams("cus_id", user_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String praiseParseNetworkResponse =  response.body().string();
                        Gson gson = new Gson();
                        //Log.e(TAG,"praiseParseNetworkResponse============>"+praiseParseNetworkResponse);
                        final AddCircleBean addCircleBean = gson.fromJson(praiseParseNetworkResponse,AddCircleBean.class);
                        if(addCircleBean.errorCode == 200 ){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),"取消关注成功",Toast.LENGTH_SHORT).show();
                                  //  loadPayAttentionToDate();
                                    loadPayAttentionToDate();
                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),addCircleBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
